#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "mythread.h"
#include <QPushButton>
#include <QThreadPool>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // 主线程
    // 1. 创建任务类对象
    Generate *gen = new Generate;
    BubbleSort* bubble = new BubbleSort;
    QuickSort* quick = new QuickSort;

    // 检测父线程发出的starting信号，并接收，便于后面
    connect(this, &MainWindow::starting, gen, &Generate::recvNum);

    // 2. 启动子线程
    connect(ui->start, &QPushButton::clicked, this, [=]()
    {
        emit starting(10000); // 启动并传递给子线程 参数
        QThreadPool::globalInstance()->start(gen); // 启动创建随机数线程
    });

    connect(gen, &Generate::sendVector, bubble, &BubbleSort::recvVector);
    connect(gen, &Generate::sendVector, quick, &QuickSort::recvVector);
    // 3. 接收子线程传递的num
    connect(gen, &Generate::sendVector, this, [=](QVector<int> qv)
    {
        QThreadPool::globalInstance()->start(bubble);
        QThreadPool::globalInstance()->start(quick);

        // 将获取到的随机数插入到随机数列表框中
        for(int i = 0; i < qv.size(); ++i)
        {
            ui->RandList->addItem(QString::number(qv.at(i)));
        }
    });

    connect(bubble, &BubbleSort::finish, this, [=](QVector<int> qv)
    {
        for(int i = 0; i < qv.size(); ++i)
        {
            ui->bubbleList->addItem(QString::number(qv.at(i)));
        }
    });
    connect(quick, &QuickSort::finish, this, [=](QVector<int> qv)
    {
        for(int i = 0; i < qv.size(); ++i)
        {
            ui->quickList->addItem(QString::number(qv.at(i)));
        }
    });

    // 不需要手动释放资源 - 由线程池维护
//    connect(this, &MainWindow::destroy, this, [=]() // 释放资源
//    {
//        gen->quit();
//        gen->wait();
//        gen->deleteLater();  // delete t1;

//        bubble->quit();
//        bubble->wait();
//        bubble->deleteLater();

//        quick->quit();
//        quick->wait();
//        quick->deleteLater();
//    });
}

MainWindow::~MainWindow()
{
    delete ui;
}

